import React, {useState,useEffect} from 'react';
import {Form, Button, DatePicker, Modal, Row, Col, message, Upload, Input, Select} from 'antd';
const FormItem = Form.Item;
import { UploadOutlined } from '@ant-design/icons';
import {getUploadUrl} from "@/utils/upload";
import moment from 'moment';
import { contractTypeStatusList,signRemarkList,contractTimeTypeData } from '@/utils/constant';
import {getContractSubjectList} from '../service';
import {resultDate} from '@/utils/utils';

const { Option } = Select;
const { RangePicker } = DatePicker;
const formLayout = {
  labelCol: { span: 7 },
};

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

const CompleteAddForm = (props) => {
  const { onSubmit, onCancel,record, loading,visible,type} = props;
  const [form] = Form.useForm();
  const [fileName, setFileName] = useState(null);
  const [fileUploadUrls, setFileUploadUrls] = useState([]);
  const [contractData,setContractData] = useState([]);
  const [employerCompany,setEmployerCompany] = useState(null);
  const [deadline,setDeadline] = useState(true);
  const [disabledData,setDisabledData] = useState([true,true]);


  const fileList = {
    name: 'file',
    multiple: true,
    action: getUploadUrl(),
    data: {name: fileName,catlog:'contract'},
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls, res.file.response]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1) {
        urls.splice(index, 1);
        setFileUploadUrls(urls);
      }
    },
  };

  useEffect(() => {
    if(visible){
      setDisabledData(type !== 'newSign' ? [true,true]:[false,false]);
      //获取合同主体
      getContractSubjectList().then(res => {
        let temp = res.filter(t => t.name === record.employerCompany)[0];
        if(type !== 'newSign' && temp){
          setEmployerCompany(temp.name);
          form.setFieldsValue({employerCompanyId:temp.id});
        }
        setContractData(res);
      });
      form.setFieldsValue({name:record.name,operateType:record.operateType});
    }
  },[visible]);

  const onFormCancel = () => {
    form.resetFields();
    onCancel();
    setFileUploadUrls([]);
    setEmployerCompany(null);
  };

  const getEnterpriseNatureInfo = (value,option) =>{
    setEmployerCompany(option.children);
  };

  const handleSelectChange = (value) =>{
    setDeadline(value === 1 ? true:false);
    if(value === 1){
      let startTime = moment(record.contractEndDate).add(1, 'd');
      let value = record.laborContractYears;
      let time = [];
      //先判断有没有合同年限时间，没有就拿开始时间及结束时间去进行计算
      if(value){
        setDisabledData([true,true]);
        let timeType = value === 0 ? 'month' : 'years';
        time = resultDate(startTime,value,timeType);
      }else{
        time = [startTime,null];
        setDisabledData([true,false]);
      }
      form.setFieldsValue({stm:null,data:time});
    }else{
      form.setFieldsValue({data:[]});
    }
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    form.resetFields();
    onSubmit({
      ...fieldsValue,
      id:record.id,
      createTime:moment(fieldsValue.data[0]).format('YYYY-MM-DD HH:mm:ss'),
      downloadDocUrl:fileUploadUrls.join(','),
      employerCompany:employerCompany,
      contractBeginDate:fieldsValue.data ? fieldsValue.data[0] : fieldsValue.stm,
      contractEndDate:fieldsValue.data && fieldsValue.data[1],
    });
    setFileUploadUrls([]);
    setEmployerCompany(null);
  };


  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="name" label="签订人">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="contractType" label="合同类型" rules={[{ required: true, message: '请选择合同类型！' }]}>
              <Select placeholder="请选择合同类型">
                {contractTypeStatusList.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col span={type === 'newSign' ? 0 : 8}>
            <FormItem name="contractTimeType" label="续签类型" rules={type === 'newSign' ?'':[{required: true, message: '续签类型不能为空'}]}>
              <Select placeholder="请选择续签类型" onChange={handleSelectChange}>
                {contractTimeTypeData.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            {deadline ?
            <FormItem name="data" label="合同起止日期">
              <RangePicker disabled={disabledData} className='widthStyle'/>
            </FormItem> :
            <FormItem name="stm" label="合同开始日期">
              <DatePicker className='widthStyle'/>
            </FormItem>
            }
          </Col>
          <Col {...colStyle}>
            <FormItem name="operateType" label="签署原因">
              <Select disabled={true} placeholder="请选择签署原因">
                {signRemarkList.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row  gutter={24}>
          <Col span={12} pull={1} style={{paddingLeft:0}}>
            <FormItem name="employerCompanyId" label="甲方主体"  rules={[{required: true, message: '甲方主体不能为空'}]}>
              <Select placeholder="请选择甲方主体" disabled={type !== 'newSign' && employerCompany ? true : false}  onChange={getEnterpriseNatureInfo} showSearch filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} allowClear>
                { contractData.length>0 ? contractData.map((item, index) => {
                  return (
                    <Option value={item.id} key={index} lable={item}>
                      {item.name}
                    </Option>
                  )
                }) : ''}
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="fileUrl" label="合同附件" rules={[{required: true, message: '合同附件不能为空'}]}>
              <Upload {...fileList}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </FormItem>
          </Col>
      </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" onClick={() => handleSubmit()} loading={loading}>提交</Button>
      </>
    )
  };

  return (
    <Modal
      width={'60%'}
      destroyOnClose
      centered
      title='线下签订合同'
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
};

export default (CompleteAddForm);
